<script setup>
import examApi from '@/api/examApi'
import paperApi from '@/api/paperApi'
import scoreApi from '@/api/scoreApi'
import useCountDown from '../../utils/useCountDown';
import { reactive } from 'vue';

import useUserInfo from '@/store/user';

const userInfo = useUserInfo()
const { m, s, h, start, stop } = useCountDown()
const route = useRoute()
const paper = ref({
    title: '',
    paperType: { title: '' },
    subject: { title: '' },
    paperQuestionGroups: []
})

const scoreInfo = reactive({
    examID: '',
    result: 100,
    studentID: '',
    errorList: [] // 错题本
})

const breadNavList = ref([
    {
        name: '首页',
        path: '/my'
    },
    {
        name: '我的考试',
        path: '/exam'
    }
])
const mode = ref('exam') // review
onMounted(async () => {
    const examId = route.query.id
    mode.value = route.query.mode || 'exam'

    examInfo.value = await examApi.getDetail(examId)
    scoreInfo.examID = examId * 1
    scoreInfo.studentID = userInfo.data.user.id


    const paperId = examInfo.value.paperID
    const res = await paperApi.getDetail(paperId)
    res.paperQuestionGroups.forEach((item) => {
        item.paperQuestions.forEach((question) => {
            question.myAns = ""
        })
    })
    paper.value = res

    breadNavList.value.push({
        name: res.title,
        path: '/paper/detail?id=' + paperId
    })

    if (mode.value == 'review') {

    } else if (mode.value == 'exam') {
        // 考试倒计时开始
        start(res.duration || 90)
    }
})

const goto = (idx) => {
    const el = document.getElementById(idx)
    el.scrollIntoView({ behavior: 'smooth' })
}

const examInfo = ref({
    title: ""
})
const ansInfo = reactive({
    ids: [],
    score: [],
    isRight: [],
    isRightIds: {},
    rightAns: [],
    myAns: []
})
const isSubmit = ref(false)
// 交卷子
const hSubmit = () => {
    try {
        paper.value.paperQuestionGroups.forEach((item) => {
            item.paperQuestions.forEach((it) => {
                const type = it.question.type;
                ansInfo.ids.push(it.no)
                ansInfo.score.push(it.score)

                ansInfo.myAns.push(it.myAns)

                if (type == 'single') {
                    if (!it.myAns) {
                        throw new Error("请完成所有题目")
                    }
                    ansInfo.rightAns.push(it.question.contentSelect.answer)
                    const isRight = it.myAns == it.question.contentSelect.answer
                    if (!isRight) {
                        scoreInfo.errorList.push(it.question.id)
                    }
                    ansInfo.isRight.push(isRight)
                    ansInfo.isRightIds[it.question.id] = isRight

                } else if (type == 'judge') {
                    if (!it.myAns) {
                        throw new Error("请完成所有题目")
                    }
                    ansInfo.rightAns.push(it.question.contentJudge.answer)
                    const isRight = it.myAns == it.question.contentJudge.answer
                    if (!isRight) {
                        scoreInfo.errorList.push(it.question.id)
                    }
                    ansInfo.isRight.push(isRight)
                    ansInfo.isRightIds[it.question.id] = isRight

                }
            })
        })
    } catch (e) {
        alert(e.message)
        return
    }
    let totalScore = 0;
    ansInfo.isRight.forEach((item, idx) => {
        if (item) {
            totalScore += ansInfo.score[idx]
        }
    })
    scoreInfo.result = totalScore
    isSubmit.value = true
    console.log(scoreInfo)
    scoreInfo.errorList = scoreInfo.errorList.join(",")

    scoreApi.add(scoreInfo).then((res) => {
        stop()
        // console.log(res)
        alert("试卷提交成功，请稍等")
        setTimeout(() => {

            alert("你的考试成绩为:" + totalScore + "分")

        }, 3000)


    })
}
</script>
<template>
    <div class="container w-10/12 m-auto">
        <AppBreadCrumb :list="breadNavList"></AppBreadCrumb>
    </div>
    <div class="container w-10/12 m-auto relative">
        <app-fixed-comp :zIndex="999">
            <div class="bg-white p-4 w-full flex justify-between">
                <div>
                    <span class="mr-4">考试名称：{{ examInfo?.title }}</span>
                    <span class="mr-4" v-if="mode == 'exam'">剩余时间：{{ h }}:{{ m }}:{{ s }}</span>
                    <!-- <span>难度:</span> 简单 -->
                </div>

                <button @click="hSubmit" :disabled="isSubmit"
                    :class="isSubmit ? 'bg-gray-200' : ' hover:bg-blue-500 hover:text-white'"
                    class="px-2 py-1 border border-blue-500 text-blue-500 font-semibold rounded-lg transition duration-300">
                    {{ isSubmit ? "已交卷" : "交 卷" }}
                </button>
            </div>
        </app-fixed-comp>
    </div>

    <div class="container w-10/12 m-auto">
        <div class="flex">
            <div class="w-9/12 mr-2">
                <div v-for="item in paper?.paperQuestionGroups" :key="item.id" class="d-flex">
                    <h5 class="m-4">{{ item.title }}</h5>
                    <div v-for="(it, idx) in item.paperQuestions" :key="it.id">
                        <AppPaperSubjectItem :mode="isSubmit ? 'ansview' : 'exam'" :type="it.title" :paperQuestion="it"
                            :idx="idx + 1" />
                    </div>
                </div>
            </div>
            <div class="w-3/12 ml-2 top-5 right-5">
                <app-fixed-comp>
                    <div class="box mt-4 p-4" v-for="(item, j) in paper?.paperQuestionGroups" :key="j">
                        <h4>{{ item.title }}</h4>
                        <div>
                            <ul class="grid grid-cols-5 gap-4 p-1">
                                <li class=" px-1 py-1 rounded-md text-center cursor-pointer"
                                    :class="isSubmit ? (ansInfo.isRightIds[i.question.id] ? 'bg-green-500' : 'bg-red-500') : (i.myAns ? 'bg-blue-500 color-white' : 'bg-gray-100')"
                                    v-for="(i, idx) in item?.paperQuestions" :key="idx"
                                    @click="goto('subject' + i.question.id)">
                                    {{ idx + 1 }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </app-fixed-comp>
            </div>
        </div>
    </div>

</template>
